import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Select {
    public void selectFromTable() throws SQLException {
        //1.创建数据源 DataSource
        DataSource dataSource = new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/java109_5?characterEncoding=utf8&useSSL=false");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("123456");
        //2.创建连接
        Connection connection = dataSource.getConnection();
        //3.构造 sql 语句
        String sql = "Select * from student";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //4.执行 sql 语句
        ResultSet resultSet = preparedStatement.executeQuery();
        //5.遍历查询结果
        while(resultSet.next()){
            int id = resultSet.getInt("id");
            String name = resultSet.getString("name");
            System.out.println("id = " + id + ", name = " + name);
        }
        //5.释放资源
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
